package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@RestController("adminDishController")
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags="菜品相关接口")
public class DishController {
    @Resource
    private DishService dishService;

    @Resource
    private RedisTemplate redisTemplate;

    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
    @PostMapping
    @ApiOperation(value = "新增菜品")
    public Result insertDishWithFlavors(@RequestBody DishDTO dishDTO){
        dishService.insertDishWithFlavors(dishDTO);

        //清理缓存数据
       /* String key ="dish_"+dishDTO.getCategoryId();
        redisTemplate.delete(key);*/
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation(value = "菜品分页查询")
    public Result<PageResult> Page(DishPageQueryDTO dishPageQueryDTO){

        PageResult pageResult= dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);

    }

    @DeleteMapping
    @ApiOperation(value = "批量删除菜品")
    //@RequestParam动态解析字符串并提取id,如1,2,3可提取1 2 3
    public Result delete(@RequestParam List<Long> ids){
        dishService.deleteBatch(ids);

        //清理缓存数据
        cleanCache("dish_*");

        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询菜品")
    public Result<DishVO> selectById(@PathVariable Long id){
        DishVO dishVO=dishService.selectById(id);
        return Result.success(dishVO);
    }

    @PutMapping
    @ApiOperation(value = "修改菜品")
    public Result update(@RequestBody DishDTO dishDTO){
        dishService.updateWithFlavor(dishDTO);

        //清理缓存数据
        cleanCache("dish_*");

        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation(value = "根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        List<Dish> dishs=dishService.selectByCategoryId(categoryId);
        return Result.success(dishs);
    }

    @PostMapping("/status/{status}")
    @ApiOperation(value = "菜品起售、停售")
    public Result status(@PathVariable Integer status ,Long id){
        dishService.status(status,id);

        //清理缓存数据
        cleanCache("dish_*");

        return Result.success();
    }
}
